import { NextRequest, NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { ResponseUtil } from '@/utils/response';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const sortBy = searchParams.get('sortBy') || 'viewCount'; // 支持多种排序方式
    const limit = parseInt(searchParams.get('limit') || '20');

    // 构建排序条件
    let orderBy: any = {};
    switch (sortBy) {
      case 'viewCount':
        orderBy = { viewCount: 'desc' };
        break;
      case 'commentCount':
        orderBy = { commentCount: 'desc' };
        break;
      case 'likeCount':
        orderBy = { likeCount: 'desc' };
        break;
      case 'createdAt':
        orderBy = { createdAt: 'desc' };
        break;
      default:
        orderBy = { viewCount: 'desc' };
    }

    // 获取排行榜帖子
    const topPosts = await prisma.forumPost.findMany({
      where: {
        status: {
          in: ['PUBLISHED', 'PENDING'] // 获取已发布或未审核状态的帖子
        },
        isDeleted: false,    // 不获取已删除的帖子
        viewCount: { gt: 0 }, // 只获取有浏览量的帖子
      },
      select: {
        id: true,
        title: true,
        viewCount: true,
        commentCount: true,
        createdAt: true,
        coverUrl: true,
        likeCount: true,
        section: {
          select: {
            id: true,
            name: true,
            category: {
              select: {
                id: true,
                name: true,
              },
            },
          },
        },
        author: {
          select: {
            id: true,
            nickname: true,
            avatar: true,
          },
        },
      },
      orderBy,
      take: Math.min(limit, 50), // 限制最大数量为50
    });

    // 格式化数据，添加排名
    const formattedPosts = topPosts.map((post, index) => ({
      ...post,
      id: post.id.toString(),
      rank: index + 1,
    }));

    return ResponseUtil.success(formattedPosts);
  } catch (error) {
    console.error('获取论坛排行榜失败:', error);
    return ResponseUtil.error('获取排行榜失败');
  }
} 